<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1200px">
    <el-tabs v-model="activeTab" class="form-tabs">
      <el-tab-pane label="基础信息" name="basic">
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="120px"
          class="contract-form"
          v-loading="formLoading"
        >
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="合同编号" prop="contractNumber">
                <el-input
                  v-model="formData.contractNumber"
                  disabled
                  placeholder="使用系统编号"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-form-item label="合同主题" prop="contractSubject">
              <el-input
                v-model="formData.contractSubject"
                placeholder="请输入"
                show-word-limit
                maxlength="16"
              />
            </el-form-item>
            <el-col :span="8">
              <el-form-item label="客户" prop="customerId">
                <el-select
                  v-model="formData.customerId"
                  placeholder="请选择客户"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="customer in customerList"
                    :key="customer.id"
                    :label="customer.name"
                    :value="customer.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="签订日期" prop="signingDate">
                <el-date-picker
                  v-model="formData.signingDate"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同开始时间" prop="startTime">
                <el-date-picker
                  v-model="formData.startTime"
                  type="date"
                  placeholder="请选择"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同终止时间" prop="endTime">
                <el-date-picker
                  v-model="formData.endTime"
                  type="date"
                  placeholder="请选择"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="销售专员" prop="salespersonId">
                <el-select v-model="formData.salespersonId" placeholder="请选择销售专员" clearable>
                  <el-option
                    v-for="person in salesPersons"
                    :key="person.id"
                    :label="person.name"
                    :value="person.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="附加说明" prop="additionalNotes">
                <el-input
                  v-model="formData.additionalNotes"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入附加说明"
                  show-word-limit
                  maxlength="500"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="摘要" prop="summary">
                <el-input
                  v-model="formData.summary"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入摘要"
                  show-word-limit
                  maxlength="500"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="预付款金额" prop="payment">
                <el-input-number
                  v-model="formData.payment"
                  :min="0"
                  :precision="2"
                  :step="1000"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="尾款金额" prop="balance">
                <el-input-number
                  v-model="formData.balance"
                  :min="0"
                  :precision="2"
                  :step="1000"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="销售类型" prop="salesType">
                <el-select v-model="formData.salesType" placeholder="请选择销售类型" clearable>
                  <el-option label="普通销售" value="普通销售" />
                  <el-option label="直销" value="直销" />
                  <el-option label="经销" value="经销" />
                  <el-option label="代销" value="代销" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户订单编号" prop="customerOrderNo">
                <el-input v-model="formData.customerOrderNo" placeholder="请输入客户订单编号" />
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="附件" prop="attachments">
                <el-upload
                  v-model:file-list="fileList"
                  class="upload-file"
                  action=""
                  multiple
                  :auto-upload="false"
                  :on-change="handleFileChange"
                >
                  <el-button type="primary">选择文件</el-button>
                  <template #tip>
                    <div class="el-upload__tip"> 上传合同相关文档（PDF, Word, Excel等） </div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <el-tabs v-model="activeTab">
      <el-tab-pane label="支付说明" name="basic">
        <el-form ref="paymentFormRef" :model="formData" label-width="120px" class="payment-form">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="合同总金额" prop="contractAmount">
                <el-input
                  v-model="formData.contractAmount"
                  placeholder="请输入合同总金额"
                  type="number"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="支付方式" prop="paymentMethod">
                <el-select
                  v-model="formData.paymentMethod"
                  placeholder="请选择支付方式"
                  clearable
                  class="payment-select"
                >
                  <el-option label="现金" value="现金" />
                  <el-option label="银行转账" value="银行转账" />
                  <el-option label="支付宝" value="支付宝" />
                  <el-option label="微信支付" value="微信支付" />
                  <el-option label="支票" value="支票" />
                  <el-option label="信用证" value="信用证" />
                  <el-option label="汇票" value="汇票" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="票据类型" prop="documentType">
                <el-select
                  v-model="formData.documentType"
                  placeholder="请选择票据类型"
                  clearable
                  class="payment-select"
                >
                  <el-option label="普通发票" value="普通发票" />
                  <el-option label="增值税发票" value="增值税发票" />
                  <el-option label="专业发票" value="专业发票" />
                  <el-option label="电子发票" value="电子发票" />
                  <el-option label="收据" value="收据" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
            <el-form-item label="客户名称" prop="customerName">
              <el-input
                v-model="formData.customerName"
                placeholder="请输入客户名称"
                show-word-limit
                maxlength="16"
              />
            </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="审核状态" prop="auditStatus">
                <el-select
                  v-model="formData.auditStatus"
                  placeholder="请选择auditStatus"
                  clearable
                  class="payment-select"
                >
                  <el-option label="已审核" value="1" />
                  <el-option label="未审核" value="0" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="签订日期" prop="signingDate">
                <el-date-picker
                  v-model="formData.signDate"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开始日期" prop="startDate">
                <el-date-picker
                  v-model="formData.startDate"
                  type="date"
                  placeholder="选择开始日期"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="终止时间" prop="endDateTime">
                <el-date-picker
                  v-model="formData.endDateTime"
                  type="date"
                  placeholder="选择终止时间"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否过期" prop="isExpired">
                <el-select
                  v-model="formData.isExpired"
                  placeholder="请选择是否过期"
                  clearable
                  class="payment-select"
                >
                  <el-option label="过期" value="1" />
                  <el-option label="未过期" value="0" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同使用状态" prop="contractUseStatus">
                <el-select
                  v-model="formData.contractUseStatus"
                  placeholder="请选择合同使用状态"
                  clearable
                  class="payment-select"
                >
                  <el-option label="已使用" value="1" />
                  <el-option label="未使用" value="0" />
                </el-select>
              </el-form-item>
            </el-col>

          </el-row>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false" :disabled="formLoading">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { Plus, Delete } from '@element-plus/icons-vue'
import type { UploadFile } from 'element-plus'
import ProductList from '../../sale/quotationmanagement/components/productList.vue'
import {StockInApi, StockInVO} from '@/api/erp/sale/contract';
import * as CustomerApi from '@/api/crm/customer'
/** 合同表单组件 */
defineOptions({ name: 'ContractForm' })
const itemFormRef = ref()

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

// 弹窗控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('create')
const paymentFormRef = ref()
// 表单数据和验证规则
const formData = ref({
  contractNumber: '',
  contractTheme: '',
  customerName: '',
  customerNumber: '',
  signDate: '',
  startDate: '',
  endDate: '',
  salesPerson: '',
  additionalInfo: '',
  summary: '',
  payment: 0,
  finalPayment: 0,
  contractAmount: '',
  saleType: '',
  customerOrderNumber: '',
  paymentMethod: '',
  invoiceType: '',
  paymentNotes: '',
  attachments: [] as File[],
  images: [] as File[],
  deliveryAddresses: [] as Array<{
    recipient: string
    contact: string
    address: string
  }>,
  contactName: '',
  gender: '',
  birthday: '',
  department: '',
  position: '',
  phone: '',
  email: '',
  qq: '',
  telephone: '',
  wechat: '',
  hometown: '',
  legalRepresentative: '',
  taxNumber: '',
  accountName: '',
  bankName: '',
  bankAccount: ''
})

// 表单验证规则
const formRules = reactive({
  contractTheme: [{ required: true, message: '合同主题不能为空', trigger: 'blur' }],
  customerName: [{ required: true, message: '请选择客户', trigger: 'change' }],
  signDate: [{ required: true, message: '请选择签订日期', trigger: 'change' }],
  salesPerson: [{ required: true, message: '请选择销售专员', trigger: 'change' }],
  contractAmount: [{ required: true, message: '合同金额不能为空', trigger: 'blur' }],
  saleType: [{ required: true, message: '请选择销售类型', trigger: 'change' }]
})

// 客户和销售专员数据
const customers = ref([
  { id: 1, name: '华为技术有限公司', number: 'CUST-001' },
  { id: 2, name: '腾讯科技', number: 'CUST-002' },
  { id: 3, name: '阿里巴巴集团', number: 'CUST-003' },
  { id: 4, name: '百度在线', number: 'CUST-004' },
  { id: 5, name: '京东集团', number: 'CUST-005' }
])

const salesPersons = ref([
  { id: 1, name: '张三' },
  { id: 2, name: '李四' },
  { id: 3, name: '王五' },
  { id: 4, name: '赵六' },
  { id: 5, name: '钱七' }
])

// 标签页控制
const activeTab = ref('basic')

// 系统编号开关
const useSystemNumber = ref(true)

// 观察客户名称变化自动填充客户编号
watch(
  () => formData.value.customerName,
  (newValue) => {
    if (newValue) {
      const customer = customers.value.find((c) => c.name === newValue)
      if (customer) {
        formData.value.customerNumber = customer.number
      }
    } else {
      formData.value.customerNumber = ''
    }
  }
)

// 上传文件
const fileList = ref<UploadFile[]>([])
const imageList = ref<UploadFile[]>([])

const handleFileChange = (file: UploadFile) => {
  if (file.raw) {
    formData.value.attachmentUrl.push(file.raw as File)
  }
}

const handleImageChange = (file: UploadFile) => {
  if (file.raw) {
    // 创建预览URL
    const url = URL.createObjectURL(file.raw)
    file.url = url

    formData.value.images.push(file.raw as File)
  }
}

const handleImageRemove = (file: UploadFile) => {
  const index = imageList.value.findIndex((f) => f.uid === file.uid)
  if (index !== -1) {
    imageList.value.splice(index, 1)
    // 同时从formData中移除
    const imageIndex = formData.value.images.findIndex((f) => f.name === file.name)
    if (imageIndex !== -1) {
      formData.value.images.splice(imageIndex, 1)
    }
    // 释放对象URL
    if (file.url) {
      URL.revokeObjectURL(file.url)
    }
  }
}
const customerList = ref([]) // 客户列表的数据
// 打开弹窗方法
const formRef = ref()
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? '新增合同' : '编辑合同'
  formType.value = type

  // 如果是编辑模式，根据id加载数据
  if (id) {
    formLoading.value = true
    try {
      // 模拟API调用
      // const data = await ContractApi.getContract(id)
      // formData.value = data

      // 模拟数据
      formData.value = {
        contractNumber: 'CT20240625001',
        contractTheme: '2024年度服务器采购合同',
        customerName: '华为技术有限公司',
        customerNumber: 'CUST-001',
        signDate: '2024-06-25',
        startDate: '2024-07-01',
        endDate: '2025-06-30',
        salesPerson: '张三',
        additionalInfo: '此合同涉及敏感设备',
        summary: '华为公司服务器采购合同，金额500万',
        payment: 2000000,
        finalPayment: 3000000,
        contractAmount: 5000000,
        saleType: '直销',
        customerOrderNumber: 'PO20240625001',
        paymentMethod: '银行转账',
        invoiceType: '增值税发票',
        paymentNotes: '首付40%，尾款在设备验收后支付',
        attachments: [],
        images: []
      }

      // 重置上传列表
      fileList.value = []
      imageList.value = []
      console.log(1111222333)

      // 设置系统编号开关
      useSystemNumber.value = formData.value.contractNumber.startsWith('CT')
    } catch (error) {
      console.error('加载合同数据失败:', error)
      message.error('加载合同数据失败')
    } finally {
      formLoading.value = false
    }
  } else {
    // 新增模式，重置表单数据
    formData.value = {
      contractNumber: '',
      contractTheme: '',
      customerName: '',
      customerNumber: '',
      signDate: '',
      startDate: '',
      endDate: '',
      salesPerson: '',
      additionalInfo: '',
      summary: '',
      payment: 0,
      finalPayment: 0,
      contractAmount: 0,
      saleType: '',
      customerOrderNumber: '',
      paymentMethod: '',
      invoiceType: '',
      paymentNotes: '',
      attachments: [],
      images: []
    }

    // 重置上传列表
    fileList.value = []
    imageList.value = []
    // 获得客户列表
    customerList.value = await CustomerApi.getCustomerSimpleList()
    // 自动生成合同编号
    if (useSystemNumber.value) {
      generateContractNumber()
    }
  }
}
// 生成系统合同编号
const generateContractNumber = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = (now.getMonth() + 1).toString().padStart(2, '0')
  const day = now.getDate().toString().padStart(2, '0')

  // 这里应该是从后端获取编号序列，这里做模拟
  const seq = Math.floor(Math.random() * 1000)
    .toString()
    .padStart(3, '0')
  formData.value.contractNumber = `CT${year}${month}${day}${seq}`
}

// 观察系统编号开关变化
watch(useSystemNumber, (newVal) => {
  if (newVal) {
    generateContractNumber()
  } else {
    formData.value.contractNumber = ''
  }
})

// 提交表单
const emit = defineEmits(['success'])
// const submitForm = async () => {
//   // 验证表单
//   try {
//     await formRef.value.validate()
//   } catch (error) {
//     message.warning('请检查表单填写是否完整')
//     return
//   }
//   generateContractNumber()
//
//   formLoading.value = true
//   try {
//     // 构造提交数据
//     const formDataToSend = new FormData()
//
//     // 添加基本数据
//     Object.entries(formData.value).forEach(([key, value]) => {
//       if (key !== 'attachments' && key !== 'images') {
//         formDataToSend.append(key, value as any)
//       }
//     })
//
//     // 添加附件
//     formData.value.attachments.forEach((file) => {
//       formDataToSend.append('attachments', file)
//     })
//
//
//
//     // 调用API（模拟）
//     // if (formType.value === 'create') {
//     //   await ContractApi.createContract(formDataToSend)
//     //   message.success('合同创建成功')
//     // } else {
//     //   await ContractApi.updateContract(formData.value.id, formDataToSend)
//     //   message.success('合同更新成功')
//     // }
//
//     // 模拟API调用成功
//     setTimeout(() => {
//       message.success(formType.value === 'create' ? '合同创建成功' : '合同更新成功')
//       dialogVisible.value = false
//       emit('success')
//     }, 1000)
//   } catch (error) {
//     console.error('保存合同失败:', error)
//     message.error('保存合同失败')
//   } finally {
//     formLoading.value = false
//   }
// }
//

const submitForm = async () => {
  // 校验表单
  // await formRef.value.validate()
  // await itemFormRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as StockInVO
    if (formType.value === 'create') {
      await StockInApi.createSaleContract(data)
      message.success(t('common.createSuccess'))
    } else {
      await StockInApi.updateSaleContract(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

// 暴露方法
defineExpose({ open })
</script>

<style scoped>
.contract-form {
  max-height: 70vh;
  padding: 15px 20px 0;
  overflow-y: auto;
}

.system-number {
  display: flex;
  align-items: center;
  height: 40px;
  padding-left: 20px;
}

.form-tabs {
  margin-top: -15px;
}

.char-limit {
  position: absolute;
  right: 10px;
  bottom: 0;
  font-size: 12px;
  color: #999;
}

.upload-file,
.upload-image {
  width: 100%;
}

.upload-image :deep(.el-upload) {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

.image-item {
  position: relative;

  /* width: 100px;
  height: 100px; */
}

.image-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-actions {
  position: absolute;
  right: 0;
  bottom: 0;
  display: flex;
  width: 100%;
  padding: 0 5px;
  background: rgb(0 0 0 / 50%);
  box-sizing: border-box;
  justify-content: flex-end;
}

.image-delete {
  padding: 5px;
  color: #fff;
  cursor: pointer;
}

.image-delete:hover {
  color: #ff4d4f;
}
</style>
